<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\BuilderPlus\components\Button;
use addons\BuilderPlus\components\Column as Col;
use addons\BuilderPlus\components\Edit;
use addons\BuilderPlus\components\Search;
use addons\BuilderPlus\facade\Table;
use app\admin\validate\AdminPassword;
use app\common\tool\Result;
use app\common\model\Role;
use think\facade\View;
use think\Response;


class Admin extends Base
{
    public function getOptions(): array
    {
        return [
            'pk'       => 'id',
            'model'    => \app\common\model\Admin::class,
            'validate' => \app\admin\validate\Admin::class,
            'with'     => ['role'],
            'just'     => false,
            'fast'     => [
                'save' => '_save'
            ]
        ];
    }

    public function index(): string
    {
        return Table::init($this)
            ->addColumns([
                ['id', 'ID', fn(Col $col) => $col->width(80)],
                ['admin_name', '用户名', null, fn(Edit $e) => $e->require()],
                ['mobile', '手机号', null, fn(Edit $e) => $e->number()->require()],
                ['role_id', '角色', fn(Col $col) => $col->templet('{{d.role?d.role.title:""}}'),
                    fn(Edit $e) => $e->select(Admin::getRole())->require()
                ],
                ['password', '登录密码', fn(Col $col) => $col->hide(), fn(Edit $e) => $e->password()->type(1)->require()],
                ['comment', '备注', null, fn(Edit $e) => $e->require()],
                ['create_time', '添加时间', fn(Col $col) => $col->width(140)],
                ['status', '状态', fn(Col $col) => $col->switch('启用|禁用', '1|0')->fixed('right')],
                ['is_lock', '权限', fn(Col $col) => $col->switch('启用|禁用', '1|0')->fixed('right')]
            ])
            ->addTopButtons([
                'add',
                'password' => fn(Button $btn) => $btn->title('重置登录密码')
                    ->icon('layui-icon-leaf')
                    ->class('danger')
                    ->url(url('admin/reset')->build())
                    ->placeholder('默认密码123456')
                    ->event('prompt'),
                'deleteAll'
            ])
            ->addRightButtons(['edit', 'delete'])
            ->addSearch([
                ['admin_name__mobile__comment', '用户名/手机/备注筛选', fn(Search $search) => $search->condition('Like')],
                ['role_id', '角色类型', fn(Search $search) => $search->type('select')->optionValue(Admin::getRole())],
                ['create_time', '添加时间', fn(Search $search) => $search->type('date')]
            ])
            ->specifyQuery([['id', '>', 1]])
            ->fetch();

    }

    public static function getRole(): array
    {
        return Role::where('id', '>', 1)->column('title', 'id');
    }

    public function reset(): Response
    {
        try {
            $param = $this->request->post();
            $param['password'] = md5($param['password'] ?: '123456');
            $this->getOptions()['model']::update(['password' => $param['password']], ['id' => explode(',', $param['id'])]);
            $msg = '重置用户登录密码。ID【' . $param['id'] . '】';
            \app\common\model\Logs::adds($msg, $this->admin->id, $this->admin->admin_name);
            return Result::success('已重置');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }

    }

    public function password(): Response|string
    {
        if ($this->request->isPost()) {
            try {
                $param = $this->request->post();
                validate(AdminPassword::class)->check($param);
                if (md5($param['old']) != $this->admin->password) return Result::fail('原密码错误');
                $this->model::update(['password' => md5($param['password'])], ['id' => $this->admin->id]);
                \app\common\model\Logs::adds('管理员【' . $this->admin->admin_name . '】修改了密码');

                session('admin_id', null);
                return Result::success('已修改');
            } catch (\Exception $e) {
                return Result::fail($e->getError());
            }
        }
        return View::fetch();
    }

}
